import { ReactElement, useRef, useEffect, RefObject, useState } from 'react'
import { Form, Input, Row, Col, Space, Button, FormInstance, Select } from 'antd'
import style from './index.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import { setSearch, getSearch, awaitWrap } from '@src/assets/js/tool'
import { getEnumRequest } from './ajax'
import qs from 'query-string';

const { Item } = Form
const { Option } = Select

async function getEnum (field: string, setFileds: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getEnumRequest(field))
  if (e === null && d instanceof Array) {
    setFileds(d)
  }
}

export function formatCondition (d: { [k: string]: any }): ConditionSchema[] {
  const r: ConditionSchema[] = []
  if (typeof d.name === 'string') {
    r.push({ k: 'name', o: 'like', v: `%${d.name}%` })
  }
  if (typeof d.area === 'string') {
    r.push({ k: 'area', o: 'like', v: `%${d.area}%` })
  }
  if (typeof d.occupation === 'string') {
    r.push({ k: 'occupation', o: 'like', v: `%${d.occupation}%` })
  }
  return r
}

// 改变搜索条件
function changeSearch (d: { [k: string]: any }, params: {[k: string]: any}, setParams: (v: {[k: string]: any}) =>void): void {
  const keys = ['name', 'area', 'occupation']
  keys.forEach(key => {
    if (d[key] === undefined) {
      d[key] = undefined
    }
  })
  d.page = 1
  setParams({
    ...params,
    ...d
  })
}

function initForm (params: {[k: string]: any}, formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  if (c === null) {
    return undefined
  }
  const o = qs.parse(qs.stringify(params))
  const r: { [k: string]: any } = {}
  if (typeof o.name === 'string') {
    r.name = o.name
  }
  if (typeof o.area === 'string') {
    r.area = o.area
  }
  if (typeof o.occupation === 'string') {
    r.occupation = o.occupation
  }
  c.setFieldsValue(r)
}

interface Props {
  params: {[k: string]: any}
  setParams: (v: {[k: string]: any}) => void
}

function Main ({params, setParams}: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [areas, setAreas] = useState<string[]>([])
  const [occupations, setOccupation] = useState<string[]>([])
  useEffect(() => {
    getEnum('area', setAreas).catch(e => console.error(e))
    getEnum('occupation', setOccupation).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    initForm(params, ref)
  }, [params])
  return (
    <div className={style.container}>
      <Form ref={ref} labelCol={{ flex: '80px' }} initialValues={{ tag: '全部' }} onFinish={d => changeSearch(d, params, setParams)} onReset={() => ref.current?.submit()}>
        <Row gutter={48}>
          <Col span={8}>
            <Item label='姓名' name='name'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='地区' name='area'>
              <Select placeholder='请选择' showSearch>
                {areas.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={8}>
            <Item label='职业分类' name='occupation'>
              <Select placeholder='请选择' showSearch>
                {occupations.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={24} className={style.btns}>
            <Space>
              <Button type='primary' htmlType='submit'>查询</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

export default Main
